
package com.example.testutil.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class BitmapUtil {
    
    public static Bitmap decodeBitmapFormRes(Resources resources, int resId, int targetWidth, int targetheight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        // 设置为true,不会为bitmap分配内存,返回一个null bitmap,但图片的基本信息可以得到,宽,高.
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resId, options);
        int inSample = calculateIntSample(options, targetWidth, targetheight);
        options.inJustDecodeBounds = false;
        options.inSampleSize = inSample;
        return BitmapFactory.decodeResource(resources, resId, options);
    }

    /*
     * 计算缩放比例
     */
    public static int calculateIntSample(BitmapFactory.Options options, int targetWidth, int targetHeight) {
        if (targetWidth <= 0 || targetHeight <= 0) {
            return 1;
        }
        int inSample = 1;
        final int imgwidth = options.outWidth;
        final int imgheight = options.outHeight;
        int scalex = imgwidth / targetWidth;
        int scaley = imgheight / targetHeight;
        if (scalex > scaley && scalex > 1) {
            inSample = scalex;
        } else if (scaley > scalex && scaley > 1) {
            inSample = scaley;
        }

        // if(imgwidth >targetWidth ||imgheight > targetHeight ) {
        // final int halfwidth = imgwidth/2;
        // final int halfheight = imgheight/2;
        // while ((halfwidth/inSample >= targetWidth) && (halfheight/inSample >=
        // targetHeight)) {
        // inSample *= 2;
        // }
        // }
        Log.d("raymond", "--------------" + inSample);
        return inSample;
    }
}
